import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 得到发送的消息，存入ServletContext
 */
@WebServlet("/loginText")
public class LoginText extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name =req.getParameter("name");
        String toName =req.getParameter("toName");
        String nameText =name+toName;
        String nameText_2 =toName+name;
        Map msgMap = maps(req);
        scPlay(nameText,msgMap);
        scPlay(nameText_2,msgMap);
    }
    public void scPlay(String name,Map msgMap){
        ServletContext sc = this.getServletContext();
        Object attribute = sc.getAttribute(name);
        if (null ==attribute){
            ArrayList<Map> strArr = new ArrayList();
            strArr.add(msgMap);
            sc.setAttribute(name,strArr);
        }else {
            ArrayList<Map> strArrTwo = (ArrayList)attribute;
            strArrTwo.add(msgMap);
            sc.setAttribute(name,strArrTwo);
        }

    }
    public Map maps(HttpServletRequest req){
        String Name =req.getParameter("name");
        String toName =req.getParameter("toName");
        String time =req.getParameter("time");
        String message =req.getParameter("message");
        Map msgMap = new HashMap<>();
        msgMap.put("name",Name);
        msgMap.put("toName",toName);
        msgMap.put("time",time);
        msgMap.put("message",message);
        return msgMap;
    }
}
